﻿#region Copyright 
/*-------------------------------------------------------------------------
* 命名空间名称/文件名:    SSPivot.Common.Helpers/EmailHelper 
* CLR版本:     4.0.30319.42000
* 机器名称:    DESKTOP-NHMLO8A
* 功 能：       N/A
* 类 名：       EmailHelper
* 创建时间：  2025/5/22 16:05:14
* 版本号：      v1.0
* 创建人:        xulong
*-------------------------------------------------------------------------*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;

namespace SSPivot.Common.Helpers
{
    public class EmailHelper
    {
        public static ServiceResultBase SendMail(MailConfig config, string? toUser, string? subject, string? body, List<PreviewDto> attr = null)
        {
            ServiceResultBase result = new ServiceResultBase();

            MailMessage message = new MailMessage();
            //必须是提供smtp服务的邮件服务器 
            if (config.FromName.IsNotNullOrEmpty())
                message.From = new MailAddress(config.From, config.FromName);
            else
                message.From = new MailAddress(config.From);

            message.To.Add(new MailAddress(toUser));
            //message.CC.Add(new MailAddress("test@126.com")); 
            //message.Bcc.Add(new MailAddress("test@126.com")); 
            message.IsBodyHtml = true;
            message.BodyEncoding = Encoding.UTF8;
            message.Priority = MailPriority.High;
            message.Subject = subject;
            message.Body = body;

            if (attr != null && attr.Count > 0)
            {
                foreach (var item in attr)
                {
                    if (item != null && item.Url != null)
                    {
                        if (item.Url.StartsWith("http"))
                        {
                            System.Net.WebRequest webreq = System.Net.WebRequest.Create(item.Url);
                            System.Net.WebResponse webres = webreq.GetResponse();
                            Stream stream = webres.GetResponseStream();
                            var attc = new Attachment(stream, item.Name);
                            message.Attachments.Add(attc);
                        }
                        else
                        {
                            var attc = new Attachment(item.Url);
                            message.Attachments.Add(attc);
                        }
                    }
                }
            }

            SmtpClient client = !string.IsNullOrEmpty(config.Proxy) && config.ProxyPort.HasValue ? new SmtpClient(config.Proxy, config.ProxyPort.Value) : new SmtpClient();
            //"smtp.gmail.com"
            client.Host = config.Host;
            //Gmail使用的端口587
            client.Port = config.Port ?? 25;
            //申请的邮箱和密码 
            client.Credentials = new System.Net.NetworkCredential(config.From, config.Password);

            if (config.EnableSsl) client.EnableSsl = true;
            try
            {
                client.Send(message);
                result.Success = true;
            }
            catch (System.Exception e)
            {
                result.Msg = e.Message;
            }
            return result;
        }

        /// <summary>
        /// 异步发送邮件 独立线程
        /// </summary>
        /// <param name="to">邮件接收人</param>
        /// <param name="title">邮件标题</param>
        /// <param name="body">邮件内容</param>
        /// <param name="port">端口号</param>
        /// <returns></returns>
        public static async Task<ServiceResultBase> SendByThreadAsync(MailConfig config, string? toUser, string? subject, string? body, List<PreviewDto> attr = null)
        {
            ServiceResultBase result = new ServiceResultBase();

            MailMessage message = new MailMessage();
                //必须是提供smtp服务的邮件服务器 
                if (config.FromName.IsNotNullOrEmpty())
                    message.From = new MailAddress(config.From, config.FromName);
                else
                    message.From = new MailAddress(config.From);

                message.To.Add(new MailAddress(toUser));
                //message.CC.Add(new MailAddress("test@126.com")); 
                //message.Bcc.Add(new MailAddress("test@126.com")); 
                message.IsBodyHtml = true;
                message.BodyEncoding = Encoding.UTF8;
                message.Priority = MailPriority.High;
                message.Subject = subject;
                message.Body = body;

                if (attr != null && attr.Count > 0)
                {
                    foreach (var item in attr)
                    {
                        if (item != null && item.Url != null)
                        {
                            if (item.Url.StartsWith("http"))
                            {
                                System.Net.WebRequest webreq = System.Net.WebRequest.Create(item.Url);
                                System.Net.WebResponse webres = webreq.GetResponse();
                                Stream stream = webres.GetResponseStream();
                                var attc = new Attachment(stream, item.Name);
                                message.Attachments.Add(attc);
                            }
                            else
                            {
                                var attc = new Attachment(item.Url);
                                message.Attachments.Add(attc);
                            }
                        }
                    }
                }

                SmtpClient client = !string.IsNullOrEmpty(config.Proxy) && config.ProxyPort.HasValue ? new SmtpClient(config.Proxy, config.ProxyPort.Value) : new SmtpClient();
                //"smtp.gmail.com"
                client.Host = config.Host;
                //Gmail使用的端口587
                client.Port = config.Port ?? 25;
                //申请的邮箱和密码 
                client.Credentials = new System.Net.NetworkCredential(config.From, config.Password);

                if (config.EnableSsl) client.EnableSsl = true;
            try
            {
                await client.SendMailAsync(message);
                result.Success = true;
            }
            catch (System.Exception e)
            {
                //throw ServiceResult.Exception(e.Message);
                result.Msg = e.Message;
            }
            return result;
            
        }
    }
    /// <summary>
    /// 邮件发送配置
    /// </summary>
    public class MailConfig
    {
        /// <summary>
        /// SMTP服务器地址
        /// </summary>
        public string? Host { get; set; }

        /// <summary>
        /// 端口号
        /// </summary>
        public int? Port { get; set; }

        /// <summary>
        /// 代理服务器
        /// </summary>
        public string? Proxy { get; set; }

        /// <summary>
        /// 代理服务器端口
        /// </summary>
        public int? ProxyPort { get; set; }

        /// <summary>
        /// 是否SSL加密
        /// </summary>
        public bool EnableSsl { get; set; }

        /// <summary>
        /// 发送人
        /// </summary>
        public string? From { get; set; }
        /// <summary>
        /// 密码
        /// </summary>
        public string? Password { get; set; } 
        /// <summary>
        /// 发送人显示名称
        /// </summary>
        public string? FromName { get; set; }

    }
}
